import 'package:merchants/models/attr_value.dart';
import 'package:merchants/models/attr_value_data.dart';
import 'package:merchants/services/base-service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class AttrValueService extends BaseService {
  AttrValueService({required super.ref});

  // 获取所有规格值
  Future<List<AttrValue>> getList() async {
    final response = await get<Map<String, dynamic>>(
      '/admin/attr-value/get-list',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取规格值列表失败');
        }
        return json;
      },
    );
    final List<dynamic> records = response['data'] as List<dynamic>;
    return records
        .map((json) => AttrValue.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  // 根据规格名称ID获取规格值列表
  Future<List<AttrValue>> getListByAttrName(String attrNameId) async {
    final response = await get<Map<String, dynamic>>(
      '/admin/attr-value/get-list-by-attr-name/$attrNameId',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取规格值列表失败');
        }
        return json;
      },
    );
    final List<dynamic> records = response['data'] as List<dynamic>;
    return records
        .map((json) => AttrValue.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  // 创建规格值
  Future<String> createAttrValue(AttrValueData attrValueData) async {
    final response = await post<Map<String, dynamic>>(
      '/admin/attr-value/create',
      body: attrValueData.toJson(),
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '创建规格值失败');
        }
        return json;
      },
    );
    return response['data']['id'] as String;
  }

  // 更新规格值
  Future<void> updateAttrValue(String id, String value) async {
    await put<Map<String, dynamic>>(
      '/admin/attr-value/$id',
      body: {'value': value},
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '更新规格值失败');
        }
        return json;
      },
    );
  }

  // 删除规格值
  Future<void> deleteAttrValue(String? id) async {
    await delete<Map<String, dynamic>>(
      '/admin/attr-value/$id',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '删除规格值失败');
        }
        return json;
      },
    );
  }
}
